#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.demo.module.upload;

import cn.cloudscope.bean.DocumentUploadResult;
import cn.cloudscope.bean.DocumentUrlResult;
import cn.cloudscope.bean.YKUPResult;
import ${package}.common.bean.vo.JsonResult;
import ${package}.common.emum.ReturnCodeEnum;
import ${package}.common.utils.UUIDUtil;
import cn.cloudscope.service.StorageWorker;
import cn.cloudscope.utils.ImageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Description: TODO
 *
 * @author wangkp
 * @date 2022/1/24 16:04
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
@RestController
public class OssUploadTest {

    @Resource
    StorageWorker storageWorker;

    @PostMapping("/ossUpload")
    @ApiOperation(value = "上传文档")
    public JsonResult<DocumentUploadResult> ossUpload(@RequestParam("file") File file, @RequestParam(required = false) String folder) {
        String suffix = StringUtils.substringAfterLast(file.getName(), ".");
        File temp = new File(UUIDUtil.buildUuid() + "." + suffix);
        try {
            InputStream inputStream = new FileInputStream(file);
            int available = inputStream.available();
            if (available > 0) {
                // 将文件存储到本地
                if (!temp.exists()) {
                    boolean newFile = temp.createNewFile();
                    if (log.isDebugEnabled() && newFile) {
                        log.debug("file {} created...", temp.getName());
                    }
                }
                IOUtils.copy(inputStream, new FileOutputStream(temp));

//                YKUPResult upResult = storageWorker.upload(file.getInputStream(),temp.getName(),folder);
                YKUPResult upResult = storageWorker.uploadSingleFile(new FileInputStream(temp), file.length(), file.getName());
                String md5Hex = DigestUtils.md5Hex(inputStream);
                DocumentUploadResult result = DocumentUploadResult.builder().path(upResult.getPhyPath())
//                        .fileType(file.)
                        .md5(md5Hex)
                        .name(file.getName())
                        .suffix(suffix)
                        .size(available / 1024)
                        .build();
                if (ImageUtil.isImageType(suffix)) {
                    InputStream thumbnailStream = ImageUtil.buildThumbnail(temp);
                    if (null != thumbnailStream) {
                        storageWorker.uploadSingleFile(thumbnailStream, (available / 1024), ImageUtil.appendSuffixHyphenThumbnail(temp.getName()));
                    }
                }
                return JsonResult.success(result);
            }
        } catch (IOException e) {
            log.error("get file input stream error", e);
        } catch (Exception e) {
            log.error("error info ", e);
        } finally {
            temp.delete();
        }
        return JsonResult.getInstant(ReturnCodeEnum.ERROR);
    }

    @GetMapping("/OssDownload")
    @ApiOperation(value = "阿里云OSS下载文档")
    @ApiImplicitParam(name = "path", required = true, value = "文档路径")
    public JsonResult OssDownload(@RequestParam("path") String path, String fileName, HttpServletResponse response) {
        storageWorker.download(path);
        return JsonResult.success();
    }

    @PostMapping("/ossDelete")
    @ApiOperation(value = "删除文件")
    @ApiImplicitParam(name = "path", required = true, value = "文档路径")
    public JsonResult ossDelete(@RequestParam("path") String path) {
        try {
            storageWorker.deleteFile(path);
        } catch (Exception e) {
            log.error("error info ",e);
        }
        return JsonResult.success();
    }

    @GetMapping("/ossPreSigned")
    @ApiOperation(value = "获取文档的访问路径（而不下载文件），建议客户端进行缓存，避免频繁请求")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "path", required = true, value = "文档路径"),
            @ApiImplicitParam(name = "expiresIn", value = "过期时间")
    })
    public JsonResult<DocumentUrlResult> ossPreSigned(@RequestParam("path") String path, @RequestParam(value = "expiresIn", defaultValue = "-1", required = false) int expiresIn) {
        DocumentUrlResult documentUrl = storageWorker.getDocumentUrl(path, expiresIn);
        return JsonResult.getInstant(ReturnCodeEnum.SUCCESS, documentUrl);
    }

    @GetMapping("/ossImgUrl")
    @ApiOperation(value = "获取一个指定有效期的图片访问链接")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "path", required = true, value = "文档路径"),
            @ApiImplicitParam(name = "expiresIn", value = "过期时间")
    })
    public JsonResult<DocumentUrlResult> ossImgUrl(@RequestParam("path") String path, @RequestParam(value = "expiresIn", defaultValue = "-1", required = false) int expiresIn){
        YKUPResult ykupResult = storageWorker.createImgExpireUrl(path,expiresIn);
        DocumentUrlResult documentUrl = new DocumentUrlResult(ykupResult.getPhyPath(),ykupResult.getThumbnail(),expiresIn);
        return JsonResult.getInstant(ReturnCodeEnum.SUCCESS, documentUrl);
    }


    @GetMapping("/ossFileUrl")
    @ApiOperation(value = "创建一个指定有效期的数据访问链接")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "path", required = true, value = "文档路径"),
            @ApiImplicitParam(name = "expiresIn", value = "过期时间")
    })
    public JsonResult<DocumentUrlResult> ossFileUrl(@RequestParam("path") String path, @RequestParam(value = "expiresIn", defaultValue = "-1", required = false) int expiresIn){
        DocumentUrlResult documentUrl = new DocumentUrlResult(storageWorker.crateFileExpireUrl(path,expiresIn),null,expiresIn);
        return JsonResult.getInstant(ReturnCodeEnum.SUCCESS, documentUrl);
    }

}
